﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using Cmd.Internal;

namespace Cmd.TypeConverters
{
    public class CollectionConverter : ITypeConverter
    {
        public Type BaseType
        {
            get;
            private set;
        }

        public CollectionConverter(Type type)
        {
            BaseType = type;
        }

        public object ConvertFromString(string value)
        {
            if (!BaseType.IsCollection())
            {
                throw new ArgumentException("T must be a collection type");
            }
            if (value == null)
            {
                return null;
            }

            string[] valListStr = (value as string).Split(',');

            List<object> list = new List<object>();

            Type listType = BaseType.GetGenericArguments()[0];
            for (int i = 0; i < valListStr.Length; i++)
            {
                object val = valListStr[i].FromString(listType);
                list.Add(val);
            }
            IList arr = (IList)Activator.CreateInstance(BaseType);
            for (int i = 0; i < list.Count; i++)
            {
                arr.Add(Convert.ChangeType(list[i], listType));
            }

            return arr;
        }

        public string ConvertToString(object value)
        {
            if (value == null)
            {
                return null;
            }
            if (!BaseType.IsCollection())
            {
                throw new ArgumentException("T must be a collection type");
            }
            return string.Join(",", (value as IEnumerable).Cast<object>().Select(item => item.ToString(BaseType.GetGenericArguments()[0])));
        }
    }
}
